<template>
  <div style="background-color: #f3f3f3;">
    <div style="background-color: #f3f3f3;height:10px;" />
    <div>
      <div class="view">
        <div class="top-title">销售数据</div>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <div class="title">今天订单数</div>
              <div class="value">{{ todayCount }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <div class="title">今天成交金额</div>
              <div class="value">{{ todayAmount }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <div class="title">本月订单数</div>
              <div class="value">{{ monthCount }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <div class="title">本月成交金额</div>
              <div class="value">{{ monthAmount }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div style="margin:10px;background-color: #fff;padding:10px">
        <!-- <el-divider>待处理订单</el-divider> -->
        <div>
          <el-button v-if="storeId == 1" size="mini" @click="batchShipping">合并发货</el-button>
        </div>
        <el-tabs v-model="activeName">
          <el-tab-pane :label="shippingTitle" name="first">
            <div>
              <el-table
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                :data="orders"
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  type="selection"
                  width="55"
                />
                <el-table-column label="操作" width="100">
                  <template slot-scope="scope">
                    <div>
                      <p v-if="scope.row.status == 2">
                        <el-button type="text" @click="toCreateExpressOrder(scope.row.id)">发货</el-button>
                      </p>
                      <p>
                        <el-button v-if="scope.row.shippingStore && scope.row.shippingStore.id != 1" type="text" @click="changeStore(scope.row.id)">转总部发货</el-button>
                      </p>
                      <div v-if="scope.row.status == 3 ">
                        <p v-if="scope.row.isUploadedShippingInfo == false">
                          <el-button type="text" @click="expressWechatOrder(scope.row)">微信同步发货</el-button>
                        </p>
                        <p v-if="scope.row.shippingCompany == 'STO'">
                          <el-button type="text" @click="printExpressOrder(scope.row.id)">打印快递面单</el-button>
                        </p>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  label="订单号"
                  prop="no"
                  width="180"
                />
                <el-table-column
                  label="物流信息"
                  prop="name"
                  width="280"
                >
                  <template slot-scope="scope">
                    <div>下单门店:【{{ scope.row.store.__toString }}】</div>
                    <div>发货门店:【{{ scope.row.shippingStore.__toString }}】</div>
                    <div v-if="scope.row.shippingType == 'pickUp'">
                      客户自提
                    </div>
                    <div v-else>
                      <div>{{ scope.row.address }}</div>
                      <div>{{ scope.row.name }}({{ scope.row.phone }})</div>
                    </div>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  label="电话"
                  prop="phone"
                  width="120"
                />
                <el-table-column
                  label="地址"
                  prop="address"
                  width="280"
                /> -->
                <el-table-column label="下单时间" width="130">
                  <template slot-scope="scope">
                    <div>{{ datetimeFormat(scope.row.createdTime) }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="产品详情" width="450">
                  <template slot-scope="scope">
                    <el-table
                      :data="scope.row.items"
                      style="width: 100%"
                      :border="true"
                    >
                      <el-table-column label="购买产品">
                        <template slot-scope="item">
                          <div>{{ item.row.__metadata.specification.__metadata.product.__toString }}</div>
                        </template>
                      </el-table-column>
                      <el-table-column label="规格">
                        <template slot-scope="item">
                          <div>{{ item.row.__metadata.specification.__metadata.name }}</div>
                        </template>
                      </el-table-column>
                      <el-table-column label="编码">
                        <template slot-scope="item">
                          <div>{{ item.row.__metadata.specification.__metadata.product.__metadata.spu }}</div>
                        </template>
                      </el-table-column>
                      <el-table-column label="单价">
                        <template slot-scope="item">
                          <div>{{ item.row.__metadata.unitPrice }}</div>
                        </template>
                      </el-table-column>
                      <el-table-column label="数量">
                        <template slot-scope="item">
                          <div>{{ item.row.__metadata.quantity }}</div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>
                </el-table-column>
                <el-table-column
                  label="最终成交价"
                  prop="price"
                  width="90"
                />
                <el-table-column
                  label="订单备注"
                  prop="comment"
                  width="90"
                />
                <el-table-column label="订单状态">
                  <template slot-scope="scope">
                    <div>{{ scope.row.status == 2 ? '待发货' : '已发货' }}</div>
                    <div>{{ scope.row.shippingNo ? `快递单号:${scope.row.shippingNo}` : '' }}</div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="afterSalesTitle" name="second">
            <div>
              <el-table
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                :data="afterSalesOrders"
                style="width: 100%"
              >
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button v-if="scope.row.afterSalesStatus == 1 || scope.row.afterSalesStatus == 3 || scope.row.afterSalesStatus == 4" type="text" @click="resultAfterSales(scope.row)">操作</el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  type="index"
                  :index="indexMethod"
                />
                <el-table-column
                  label="物流信息"
                  prop="name"
                  width="280"
                >
                  <template slot-scope="scope">
                    <div>{{ scope.row.address }}</div>
                    <div>{{ scope.row.name }}({{ scope.row.address }})</div>
                  </template>
                </el-table-column>
                <el-table-column label="产品详情" width="400">
                  <template slot-scope="scope">
                    <el-table
                      :data="scope.row.items"
                      style="width: 100%"
                      :border="true"
                    >
                      <el-table-column label="购买产品">
                        <template slot-scope="item">
                          <div>{{ item.row.__metadata.specification.__metadata.product.__toString }}</div>
                        </template>
                      </el-table-column>
                      <el-table-column label="规格">
                        <template slot-scope="item">
                          <div>{{ item.row.__metadata.specification.__metadata.name }}</div>
                        </template>
                      </el-table-column>
                      <el-table-column label="数量">
                        <template slot-scope="item">
                          <div>{{ item.row.__metadata.quantity }}</div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>
                </el-table-column>
                <el-table-column label="售后要求" width="250">
                  <template slot-scope="scope">
                    <div>{{ scope.row.afterSales[0].comment }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="售后状态" width="250">
                  <template slot-scope="scope">
                    <div>
                      <el-button type="text" @click="afterSalesData(scope.row)">{{ afterSalesStatus[scope.row.afterSalesStatus] }}</el-button>
                    </div>
                    <div>
                      <el-button type="text" @click="finishAfterSale(scope.row)">线下处理</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- 售后处理流程 -->
        <el-dialog
          title="售后流程"
          :visible.sync="showAfterSalesData"
          width="50%"
        >
          <div>
            <el-steps direction="vertical" :active="resultOrder.afterSalesStatus">
              <el-step v-for="(item,index) in resultOrder.afterSales" :key="index" :title="item.title" :description="item.time + ' ' + item.comment" />
            </el-steps>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="showAfterSalesData = false">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 发货面板 -->
        <el-dialog
          title="选择快递方式"
          :visible.sync="showCompany"
          width="30%"
        >
          <div>
            <el-radio v-for="(item,index) in companys" :key="index" v-model="company" :label="item.value">{{ item.label }}</el-radio>
            <div v-if="company == 'SF'" style="margin-top:20px;width:50%;">
              <el-input v-model="shippingNumber" placeholder="请输入顺丰快递单号" />
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showCompany = false">取 消</el-button>
            <el-button type="primary" @click="createExpressOrder">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 批量发货面板 -->
        <el-dialog
          title="选择快递方式"
          :visible.sync="showBatchCompany"
          width="30%"
        >
          <div>
            <el-radio v-for="(item,index) in companys" :key="index" v-model="company" :label="item.value">{{ item.label }}</el-radio>
            <div v-if="company == 'SF'" style="margin-top:20px;width:50%;">
              <el-input v-model="shippingNumber" placeholder="请输入顺丰快递单号" />
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showBatchCompany = false">取 消</el-button>
            <el-button type="primary" @click="createBatchExpressOrder">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 处理面板 -->
        <el-dialog
          title="处理结果"
          :visible.sync="dialogVisible"
          width="30%"
        >
          <div>
            <div v-if="resultOrder.afterSalesStatus == 1">
              <p>
                <el-radio v-model="resultStatus" label="2" @change="chooseType(2)">同意售后</el-radio>
                <el-radio v-model="resultStatus" label="5" @change="chooseType(5)">不同意售后</el-radio>
              </p>
              <el-input
                v-model="result"
                type="textarea"
                :rows="2"
                :placeholder="resultPlaceholder[resultStatus]"
              />
              <!-- <el-radio v-for="(item,index) in addresses" :key="index" v-model="result" :label="item">{{ item }}</el-radio> -->
            </div>
            <div v-else>
              <el-input
                v-model="result"
                type="textarea"
                :rows="2"
                placeholder="请输入处理结果"
              />
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="resultData">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 发货单打印面板 -->
        <el-dialog
          v-if="printOrder != ''"
          title="发货单打印"
          :visible.sync="showPrint"
          width="80%"
        >
          <div>
            <div id="shipping-list-print-data" class="invoice-container">
              <!-- 发货单表格 -->
              <table class="invoice-table">
                <!-- 第1行：发货单标题 -->
                <tr>
                  <td colspan="5" class="invoice-header">发货单</td>
                </tr>

                <!-- 第2行：订单号和下单时间 -->
                <tr>
                  <td colspan="3" class="text-left">订单号: {{ printOrder.no }}</td>
                  <td colspan="2" class="text-left">下单时间: {{ datetimeFormat(printOrder.createdTime) }}</td>
                </tr>

                <!-- 第3行：产品表头 -->
                <tr>
                  <th class="table-header">商品名称</th>
                  <th class="table-header">规格</th>
                  <th class="table-header">商品编码</th>
                  <th class="table-header">商品数量</th>
                  <th class="table-header">单价</th>
                </tr>

                <!-- 第4行：产品内容 -->

                <tr v-for="(item,index) in printOrder.items" :key="index">
                  <td class="text-left">{{ item.__metadata.specification.__metadata.product.__toString }}</td>
                  <td class="text-center">{{ item.__metadata.specification.__metadata.name }}</td>
                  <td class="text-center" />
                  <td class="text-center">{{ item.__metadata.quantity }}</td>
                  <td class="text-right">¥{{ item.__metadata.unitPrice }}</td>
                </tr>

                <!-- 第5行：收件人信息 -->
                <tr>
                  <td colspan="2" class="text-left">收件人姓名: {{ printOrder.name }}</td>
                  <td colspan="3" class="text-left">收件人电话: {{ printOrder.phone }}</td>
                </tr>

                <!-- 第6行：收货地址 -->
                <tr>
                  <td colspan="5" class="text-left">收货地址: {{ printOrder.address }}</td>
                </tr>

                <!-- 第7行：备注和总计 -->
                <tr>
                  <!-- 前2列合并且跨2行 -->
                  <td rowspan="2" colspan="2" class="text-left" style="vertical-align: top;">
                    <strong>备注:</strong> {{ printOrder.comment }}
                  </td>
                  <!-- 第3列：总计 -->
                  <td class="text-right">总计:</td>
                  <!-- 后2列合并 -->
                  <td colspan="2" class="text-center">{{ getTotalCount(printOrder.items) }}件</td>
                </tr>

                <!-- 第8行：实付金额 -->
                <tr>
                  <!-- 前2列已被合并，不需要再写 -->
                  <td class="text-right">实付:</td>
                  <td colspan="2" class="text-center">¥{{ printOrder.price }}</td>
                </tr>

                <!-- 第9行：签名区域 -->
                <tr>
                  <td colspan="5" class="text-left">
                    <div>{{ printOrder.store.__toString }}</div>
                  </td>
                </tr>
              </table>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-input v-model="printOrder.comment" placeholder="发货备注" style="width:30%" />
            <el-button @click="showPrint = false">取 消</el-button>
            <el-button v-print="printShippingListObj" type="primary">打 印</el-button>
          </span>
        </el-dialog>

        <!-- 发货单打印面板 -->
        <el-dialog
          title="快递面单打印"
          :visible.sync="showPrintLabel"
          width="600px"
        >
          <div class="label-container">
            <div id="shipping-label-print-data" class="label-print-area" v-html="htmlNodes" />
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showPrintLabel = false">取 消</el-button>
            <el-button v-print="printShippingLabelObj" type="primary">打 印</el-button>
          </span>
        </el-dialog>
      </div>
    </div>

  </div>
</template>

<script>
import print from 'vue-print-nb'

export default {
  directives: {
    print
  },
  data() {
    return {
      printShippingListObj: {
        id: 'shipping-list-print-data',
        popTitle: '打印发货单',
        extraHead: '<meta http-equiv="Content-Language" content="zh-cn"/>',
        style: `
          @page { margin: 0mm; size: A4 landscape; }
          @media print {
            body { margin: 1cm; width: 100%; }
          }
        `
      },
      printShippingLabelObj: {
        id: 'shipping-label-print-data',
        extraHead: '<meta http-equiv="Content-Language" content="zh-cn"/>',
        style: `
          @page { 
            margin: 0mm; 
            size: Legal; 

            @top-left { content: none; }
            @top-center { content: none; }
            @top-right { content: none; }
            @bottom-left { content: none; }
            @bottom-center { content: none; }
            @bottom-right { content: none; }
          }
          body { margin: 0cm; }
          @media print {
            .no-print {
              display: none !important;
            }
          }
        `
      },
      afterSalesStatus: {
        1: '待客服审核',
        2: '待寄回',
        3: '待仓库验收',
        4: '待退款/确认收货'
      },
      addresses: [
        '广东省江门市蓬江区育德街51号都荟城3号门3楼，华盛咖啡，07503388884'
      ],
      isManager: false,
      orders: [],
      todayCount: 0,
      todayAmount: 0,
      monthCount: 0,
      monthAmount: 0,
      loading: true,
      shippingTitle: '待发货订单(0)',
      afterSalesTitle: '待处理售后单(0)',
      activeName: 'first',
      afterSalesOrders: [],
      resultOrder: '',
      dialogVisible: false,
      result: '',
      showPrint: false,
      showPrintLabel: false,
      printOrder: '',
      showCompany: false,
      orderId: 0,
      company: 'STO',
      companys: [
        {
          label: '申通快递',
          value: 'STO'
        },
        {
          label: '顺丰快递',
          value: 'SF'
        },
        {
          label: '客户自提',
          value: 'PMS'
        }
      ],
      htmlNodes: '',
      shippingNumber: '',
      showAfterSalesData: false,
      resultStatus: '2',
      resultPlaceholder: {
        2: '请输入回寄地址',
        5: '请输入拒绝原因'
      },
      operateOrders: [], // 批量操作的订单数组
      showBatchCompany: false,
      storeId: 0,
      apiUrl: ''
    }
  },
  created() {
    this.axios.get(`/api/user`).then((res) => {
      console.log('user', res.data)
      if (res.data.roles.indexOf('ROLE_SUPER_ADMIN') !== -1) {
        console.log('管理员登录')
        this.isManager = true
        this.apiUrl = `/manage`
      } else {
        this.storeId = res.data.stores[0].id
        this.apiUrl = `/store/${this.storeId}`
        this.companys = [
          {
            label: '顺丰快递',
            value: 'SF'
          },
          {
            label: '客户自提',
            value: 'PMS'
          }
        ]
      }
      this.getOrders()
    })
  },
  mounted() {
  },

  beforeDestroy() {
  },
  methods: {
    indexMethod(index) {
      return index + 1
    },
    toCreateExpressOrder(orderId) {
      this.orderId = orderId
      this.showCompany = true
    },
    // 同步微信的发货
    expressWechatOrder(order) {
      console.log(order)
      let logistics_type = 1
      if (order.shippingCompany === 'PMS') {
        logistics_type = 4
      }
      this.axios.post(`/api/orders/${order.id}/upload-shipping-info`, {
        delivery_mode: 1,
        logistics_type: logistics_type
      }).then((res) => {
        console.log(res)
      })
    },
    // 生成运单
    createExpressOrder() {
      const orderId = this.orderId
      this.axios.get(`${this.apiUrl}/orders/${orderId}`).then((res) => {
        // 发货门店不是自己的，又不是管理员的，不能发货
        if (this.isManager === false && res.data.shippingStore.id !== this.storeId) {
          this.$message.error('需要发货门店操作发货！')
          return
        }
        let tipText = `是否确定【${this.company === 'SF' ? '顺丰' : '申通'}】发货？`
        if (this.company === 'PMS') {
          tipText = '是否确定客户自提？'
        }
        this.$confirm(tipText, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.company === 'STO') {
            const loading = this.$loading({
              lock: true,
              text: '正在生成运单',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            const bizId = '广东江门蓬江区公司_华盛咖啡小程序商城'
            const deliveryId = 'STO'
            this.axios.post(`/api/orders/${orderId}/shipping`, { biz_id: bizId, delivery_id: deliveryId }).then((res) => {
              console.log(res.data)
              loading.close()
              if (res.data.result && res.data.result.delivery_resultcode === -1) {
                this.$message.error(res.data.result.delivery_resultmsg)
              }
              if (res.data.result && res.data.result.errcode == 0) {
                this.$message.success('生成成功！')
                // 同时需要微信发货
                this.axios.post(`/api/orders/${orderId}/upload-shipping-info`, {
                  delivery_mode: 1,
                  logistics_type: 1
                }).then((res) => {
                  console.log(res)
                })
              }
              if (res.data.result && res.data.result.errcode && res.data.result.errcode == 9300522) {
                this.$message.error('重复下单')
              }
              this.showCompany = false
              this.getOrders()
            })
          } else if (this.company === 'SF') {
          // 顺丰直接输入快递单号
            if (this.shippingNumber.trim() === '') {
              this.$message.error('请输入顺丰快递单号')
              return
            }
            const loading = this.$loading({
              lock: true,
              text: '正在发货',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            this.axios.put(`${this.apiUrl}/orders/${this.orderId}`, { shippingNo: this.shippingNumber, shippingCompany: 'SF', status: 3 }).then((res) => {
              this.$message.success('发货成功！')
              this.showCompany = false
              this.shippingNumber = ''
              // 同时需要微信发货
              this.axios.post(`/api/orders/${orderId}/upload-shipping-info`, {
                delivery_mode: 1,
                logistics_type: 1
              }).then((res) => {
                console.log(res)
              })
              loading.close()
              this.getOrders()
            })
          } else if (this.company === 'PMS') {
            const loading = this.$loading({
              lock: true,
              text: '正在同步信息',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            this.axios.put(`${this.apiUrl}/orders/${this.orderId}`, { shippingNo: '客户自提', shippingCompany: 'PMS', status: 3 }).then((res) => {
              this.$message.success('发货成功！')
              // 同时需要微信发货
              this.axios.post(`/api/orders/${orderId}/upload-shipping-info`, {
                delivery_mode: 1,
                logistics_type: 4
              }).then((res) => {
                console.log(res)
              })
              this.showCompany = false
              this.shippingNumber = ''
              loading.close()
              this.getOrders()
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '生成失败'
          })
        })
      })
    },
    // 转总部发货
    changeStore(id) {
      if (confirm('是否确定转到总部发货？')) {
        this.axios.put(`store/${this.storeId}/orders/${id}`, { shippingStore: 1 }).then((res) => {
          this.$message.success('操作成功！')
          this.getOrders()
        })
      }
    },
    // 选择
    handleSelectionChange(e) {
      this.operateOrders = e
    },
    // 批量发货操作
    batchShipping() {
      if (this.operateOrders && this.operateOrders.length > 0) {
        for (const i of this.operateOrders) {
          if (i.status !== '2') {
            this.$message.error('存在不可发货订单！')
            return
          }
        }
        this.showCompany = true
      } else {
        this.$message.error('请选择需要操作的订单！')
      }
    },
    // 生成运单
    createBatchExpressOrder() {
      if (this.operateOrders && this.operateOrders.length > 0) {
        for (const i of this.operateOrders) {
          if (i.status !== '2') {
            this.$message.error('存在不可发货订单！')
            return
          }
        }
      } else {
        this.$message.error('请选择需要操作的订单！')
      }
      const orders = this.operateOrders
      let tipText = `是否确定【${this.company === 'SF' ? '顺丰' : '申通'}】发货？`
      if (this.company === 'PMS') {
        tipText = '是否确定客户自提？'
      }
      this.$confirm(tipText, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.company === 'STO') {
          const loading = this.$loading({
            lock: true,
            text: '正在生成运单',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const bizId = '广东江门蓬江区公司_华盛咖啡小程序商城'
          const deliveryId = 'STO'
          // 批量的话，只发货第一单，然后用第一单的相关资料同步到其他的订单上面
          this.axios.post(`/api/orders/${orders[0].id}/shipping`, { biz_id: bizId, delivery_id: deliveryId }).then((res) => {
            if (res.data.result && res.data.result.delivery_resultcode === -1) {
              this.$message.error(res.data.result.delivery_resultmsg)
            }
            if (res.data.result && res.data.result.errcode && res.data.result.errcode === 9300522) {
              this.$message.error('重复下单')
            }
            if (res.data.result && res.data.result.errcode === 0) {
              const promise = []
              // 查第一张订单的物流信息
              this.request.get(`${this.apiUrl}/orders/${orders[0].id}`).then((res) => {
                for (const i of orders) {
                  promise.push(
                    this.axios.put(`${this.apiUrl}/orders/${i.id}`, { shippingNo: res.data.shippingNumber, shippingCompany: 'STO' })
                  )
                }
                Promise.all(promise).then((res) => {
                  this.$message.success('发货成功！')
                  this.showBatchCompany = false
                  this.getOrders()
                  loading.close()
                })
              })
            }
          })
        } else if (this.company === 'SF') {
          // 顺丰直接输入快递单号
          if (this.shippingNumber.trim() === '') {
            this.$message.error('请输入顺丰快递单号')
            return
          }
          const loading = this.$loading({
            lock: true,
            text: '正在发货',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const promise = []
          for (const i of orders) {
            promise.push(
              this.axios.put(`${this.apiUrl}/orders/${i.id}`, { shippingNo: this.shippingNumber, shippingCompany: 'SF' })
            )
          }
          Promise.all(promise).then((res) => {
            this.$message.success('发货成功！')
            this.showBatchCompany = false
            this.getOrders()
            loading.close()
          })
        } else if (this.company === 'PMS') {
          const loading = this.$loading({
            lock: true,
            text: '正在同步信息',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const promise = []
          for (const i of orders) {
            promise.push(
              this.axios.put(`${this.apiUrl}/orders/${this.orderId}`, { shippingNo: '客户自提', shippingCompany: 'PMS' })
            )
          }
          Promise.all(promise).then((res) => {
            this.$message.success('发货成功！')
            this.showBatchCompany = false
            this.getOrders()
            loading.close()
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '生成失败'
        })
      })
    },
    // 取消运单
    cancelExpressOrder(orderId) {
      this.$confirm('是否确定取消运单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post(`/api/orders/${orderId}/cancel-shipping`).then((res) => {
          this.$message.success('取消成功！')
          this.getOrders()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '生成失败'
        })
      })
    },
    resultData() {
      // 1: 审核并填写回寄地址 3：仓库确认收货
      if (this.resultOrder.afterSalesStatus === 3) {
        this.result = `仓库确认收到回寄货物` + this.result
      }
      if (this.result.trim() === '') {
        this.$message.error('请输入处理结果')
        return
      }
      const date = new Date()
      const afterSales = this.resultOrder.afterSales
      afterSales[this.resultOrder.afterSalesStatus].comment = this.result
      afterSales[this.resultOrder.afterSalesStatus].time = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
      this.axios.put(`${this.apiUrl}/orders/${this.resultOrder.id}`, { afterSales: afterSales, afterSalesStatus: this.resultOrder.afterSalesStatus === 1 ? this.resultStatus : parseInt(this.resultOrder.afterSalesStatus) + 1 }).then((res) => {
        this.$message.success('处理成功！')
        this.dialogVisible = false
        this.getOrders()
      })
    },
    // 查看售后情况
    afterSalesData(order) {
      this.resultOrder = order
      console.log('order', order)
      this.showAfterSalesData = true
    },
    finishAfterSale(order) {
      console.log(order)
      if (confirm('线下处理将跳过所有流程，是否确定线下处理？')) {
        const time = new Date()
        const afterSales = order.afterSales
        afterSales.push({
          comment: '线下处理',
          time: `${time.getFullYear()}/${time.getMonth() + 1}/${time.getDate()} ${time.getHours()}:${time.getMinutes()}`,
          title: '线下处理'
        })
        this.axios.put(`${this.apiUrl}/orders/${order.id}`, { afterSales: afterSales, afterSalesStatus: 5 }).then((res) => {
          this.$message.success('操作成功！')
          this.getOrders()
        })
      }
    },
    printExpressOrder(orderId) {
      this.axios.get(`/public/orders/${orderId}/get-shipping`).then((res) => {
        console.log('运单信息', res.data)
        this.htmlNodes = this.decodeBase64(res.data.print_html)
        this.showPrintLabel = true
      })
    },
    // Base64 解码（含中文处理）
    decodeBase64(base64Str) {
      const rawData = atob(base64Str)
      const uintArray = new Uint8Array(rawData.length)

      for (let i = 0; i < rawData.length; i++) {
        uintArray[i] = rawData.charCodeAt(i)
      }

      try {
        return new TextDecoder('utf-8').decode(uintArray)
      } catch (e) {
        console.error('Decoding error:', e)
        return rawData // 回退到原始解码
      }
    },
    printShippingOrder(order) {
      console.log('print', order)
      this.printOrder = order
      this.showPrint = true
    },
    resultAfterSales(order) {
      this.resultOrder = order
      if (order.afterSalesStatus == 1) {
        this.result = '广东省江门市蓬江区育德街51号都荟城3号门3楼，华盛咖啡，07503388884'
      } else {
        this.result = ''
      }
      this.dialogVisible = true
    },
    chooseType(type) {
      if (type === 2) {
        this.result = '广东省江门市蓬江区育德街51号都荟城3号门3楼，华盛咖啡，07503388884'
      } else {
        this.result = ''
      }
    },
    // 打印
    printData() {},

    // 日期格式化
    datetimeFormat(time) {
      const date = new Date(time)
      return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
    },
    getTotalCount(items) {
      let count = 0
      for (const i of items) {
        count += parseInt(i.__metadata.quantity)
      }
      return count
    },
    getOrders() {
      // 获取待发货订单
      this.axios.get(`${this.apiUrl}/orders`, { params: {
        '@filter': `entity.getStatus() == 2 || entity.getStatus() == 3`,
        '@expands': "['entity.items.specification.product']",
        '@order': 'entity.createdTime|DESC'
      }}).then((res) => {
        console.log('orders', res.data)
        this.orders = res.data
        this.shippingTitle = `待发货订单(${this.orders.length})`
        this.loading = false
      })
      // 查售后订单
      this.axios.get(`${this.apiUrl}/orders`, { params: {
        '@filter': `entity.getAfterSalesStatus() >= 1 && entity.getAfterSalesStatus() < 5`,
        '@expands': "['entity.items.specification']"
      }}).then((res) => {
        console.log('orders', res.data)
        this.afterSalesOrders = res.data
        this.afterSalesTitle = `待处理售后单(${this.afterSalesOrders.length})`
      })
      // 获取今天以及当月时间，然后计算订单数以及相关金额
      const date = new Date()
      const today = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
      const firstDate = `${date.getFullYear()}/${date.getMonth() + 1}/01`
      this.axios.get(`${this.apiUrl}/orders`, { params: {
        '@filter': `entity.getPaidTime() >= datetime.get('${today} 00:00:00') && entity.getStatus() >= 2`,
        '@select': 'COUNT(entity.id) as totalCount,SUM(entity.price) as totalPrice'
      }}).then((res) => {
        console.log('total', res.data)
        this.todayCount = res.data[0].totalCount
        this.todayAmount = res.data[0].totalPrice ? res.data[0].totalPrice : 0
      })
      this.axios.get(`${this.apiUrl}/orders`, { params: {
        '@filter': `entity.getPaidTime() >= datetime.get('${firstDate} 00:00:00') && entity.getStatus() >= 2`,
        '@select': 'COUNT(entity.id) as totalCount,SUM(entity.price) as totalPrice'
      }}).then((res) => {
        console.log('Monthtotal', res.data)
        this.monthCount = res.data[0].totalCount
        this.monthAmount = res.data[0].totalPrice ? res.data[0].totalPrice : 0
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .label-container {
    /* Remove all other style effect */
    all: initial;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .label-print-area {
    all: initial;
    zoom: 0.340;
  }

  .grid-content{
    text-align: center;
  }
  .title{
    margin:10px;
    font-size: 20px;
    color:#000;
    font-weight: bold;
  }
  .value{
    font-size: 28px;
    color:#000;
  }
  .view{
    background-color: #fff;
    border-radius: 10px;
    margin:20px;
    padding:10px;
  }

  .top-title{
    color:#000;
    font-size:23px;
    margin: 10px;
  }

    .container {
            max-width: 1000px;
            width: 100%;
            margin: 20px auto;
            padding: 30px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        }

        header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: linear-gradient(90deg, #1e88e5, #0d47a1);
            color: white;
            border-radius: 12px;
        }

        h1 {
            font-size: 2.2rem;
            margin-bottom: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
        }

        .subtitle {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .invoice-container {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            margin-bottom: 30px;
            border: 1px solid #e0f7fa;
        }

        .company-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 20px;
            border-bottom: 2px dashed #b3e5fc;
        }

        .company-logo {
            font-size: 40px;
            color: #0288d1;
        }

        .company-details {
            text-align: right;
        }

        .invoice-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 22px;
            margin: 20px 0;
        }

        .invoice-table th,
        .invoice-table td {
            border: 1px solid #000;
            padding: 18px 16px;
        }

        .invoice-header {
            // background: linear-gradient(90deg, #1e88e5, #0d47a1);
            color: #000;
            font-size: 24px;
            font-weight: bold;
            text-align: center;
        }

        .table-header {
            // background-color: #e1f5fe;
            color: #000;
            font-weight: 600;
            text-align: center;
        }

        .text-left {
            text-align: left;
            color:#000;
        }

        .text-right {
            text-align: right;
            color:#000;
        }

        .text-center {
            text-align: center;
            color:#000;
        }

        .total-row {
            // background-color: #e1f5fe;
            font-weight: bold;
        }

        .signature-area {
            padding: 30px 10px;
            text-align: center;
            margin-top: 20px;
            border-top: 1px dashed #b3e5fc;
        }

        .action-buttons {
            display: flex;
            gap: 20px;
            justify-content: center;
            margin-top: 30px;
        }

        .btn {
            padding: 14px 35px;
            border: none;
            border-radius: 8px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 12px;
            transition: all 0.3s;
        }

        .btn-print {
            background: linear-gradient(135deg, #1e88e5, #1565c0);
            color: white;
            box-shadow: 0 5px 15px rgba(33, 150, 243, 0.3);
        }

        .btn-print:hover {
            background: linear-gradient(135deg, #2196f3, #0d47a1);
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(33, 150, 243, 0.4);
        }

        .btn-reset {
            background: linear-gradient(135deg, #26c6da, #00838f);
            color: white;
            box-shadow: 0 5px 15px rgba(38, 198, 218, 0.3);
        }

        .btn-reset:hover {
            background: linear-gradient(135deg, #4dd0e1, #006064);
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(38, 198, 218, 0.4);
        }

        .footer {
            text-align: center;
            margin-top: 30px;
            padding: 20px;
            color: #000;
            font-size: 14px;
            border-top: 1px solid #e0f7fa;
        }
</style>
